//
// Created by ljy on 10/28/21.
//
#include <linux/mmzone.h>
#include <asm-i386/page.h>
#include <linux/bootmem.h>
#include <linux/mm.h>
#include <linux/list.h>
#include <asm-i386/i2c.h>
#include <linux/string.h>
#include <asm-i386/bitops.h>
#include <linux/spin_lock.h>
#include <linux/debug.h>
#include <linux/swap.h>

#define LONG_ALIGN(x) (((x)+(sizeof(long))-1)&~((sizeof(long))-1))
int nr_swap_pages;
int nr_active_pages;
int nr_inactive_pages;
/*
 * Temporary debugging check.
 */
#define BAD_RANGE(zone, page)						\
(									\
	(((page) - mem_map) >= ((zone)->zone_start_mapnr+(zone)->size))	\
	|| (((page) - mem_map) < (zone)->zone_start_mapnr)		\
	|| ((zone) != page_zone(page))					\
)

#define MARK_USED(index, order, area) \
	__change_bit((index) >> (1+(order)), (area)->map)

zone_t *zone_table[MAX_NR_ZONES*MAX_NR_NODES];
static char *zone_names[MAX_NR_ZONES] = { "DMA", "Normal", "HighMem" };
static int zone_balance_ratio[MAX_NR_ZONES]  = { 128, 128, 128, };
static int zone_balance_min[MAX_NR_ZONES]  = { 20 , 20, 20, };
static int zone_balance_max[MAX_NR_ZONES]  = { 255 , 255, 255, };
pg_data_t *pgdat_list;

static inline struct page * expand (zone_t *zone, struct page *page,
                                    unsigned long index, int low, int high, free_area_t * area)
{
    unsigned long size = 1 << high;

    while (high > low) {
        if (BAD_RANGE(zone,page))
            BUG();
        area--;
        high--;
        size >>= 1;
        list_add(&(page)->list, &(area)->free_list);
        MARK_USED(index, high, area);
        index += size;
        page += size;
    }
    if (BAD_RANGE(zone,page))
        BUG();
    return page;
}

static inline void build_zonelists(pg_data_t *pgdat)
{
    int i, j, k;

    for (i = 0; i <= GFP_ZONEMASK; i++) {
        zonelist_t *zonelist;
        zone_t *zone;

        zonelist = pgdat->node_zonelists + i;
        memset(zonelist, 0, sizeof(*zonelist));

        j = 0;
        k = ZONE_NORMAL;
        if (i & __GFP_HIGHMEM)
            k = ZONE_HIGHMEM;
        if (i & __GFP_DMA)
            k = ZONE_DMA;

        switch (k) {
            default:
                //BUG();
                /*
                 * fallthrough:
                 */
            case ZONE_HIGHMEM:
                zone = pgdat->node_zones + ZONE_HIGHMEM;
                if (zone->size) {
                    zonelist->zones[j++] = zone;
                }
            case ZONE_NORMAL:
                zone = pgdat->node_zones + ZONE_NORMAL;
                if (zone->size)
                    zonelist->zones[j++] = zone;
            case ZONE_DMA:
                zone = pgdat->node_zones + ZONE_DMA;
                if (zone->size)
                    zonelist->zones[j++] = zone;
        }
        zonelist->zones[j++] = NULL;
    }
}


/*
 * Set up the zone data structures:
 *   - mark all pages reserved
 *   - mark all memory queues empty
 *   - clear the memory bitmaps
 */
void free_area_init_core(int nid, pg_data_t *pgdat, struct page **gmap,
                                unsigned long *zones_size, unsigned long zone_start_paddr,
                                unsigned long *zholes_size, struct page *lmem_map)
{
    unsigned long i, j;
    unsigned long map_size;
    unsigned long totalpages, offset, realtotalpages;
    const unsigned long zone_required_alignment = 1UL << (MAX_ORDER-1);

    if (zone_start_paddr & ~PAGE_MASK){
//        BUG();
    }
    totalpages = 0;
    for (i = 0; i < MAX_NR_ZONES; i++) {
        unsigned long size = zones_size[i];
        totalpages += size;
    }
    realtotalpages = totalpages;
    if (zholes_size)
        for (i = 0; i < MAX_NR_ZONES; i++)
            realtotalpages -= zholes_size[i];

//    printk("On node %d totalpages: %lu\n", nid, realtotalpages);

    /*
     * Some architectures (with lots of mem and discontinous memory
     * maps) have to search for a good mem_map area:
     * For discontigmem, the conceptual mem map array starts from
     * PAGE_OFFSET, we need to align the actual array onto a mem map
     * boundary, so that MAP_NR works.
     */
    map_size = (totalpages + 1)*sizeof(struct page);
    if (lmem_map == (struct page *)0) {
        lmem_map = (struct page *) alloc_bootmem_node(pgdat, map_size);
        lmem_map = (struct page *)(PAGE_OFFSET +
                                   MAP_ALIGN((unsigned long)lmem_map - PAGE_OFFSET));
    }
    *gmap = pgdat->node_mem_map = lmem_map;
    pgdat->node_size = totalpages;
    pgdat->node_start_paddr = zone_start_paddr;
    pgdat->node_start_mapnr = (lmem_map - mem_map);
    pgdat->nr_zones = 0;

    offset = lmem_map - mem_map;
    for (j = 0; j < MAX_NR_ZONES; j++) {
        zone_t *zone = pgdat->node_zones + j;
        unsigned long mask;
        unsigned long size, realsize;

        zone_table[nid * MAX_NR_ZONES + j] = zone;
        realsize = size = zones_size[j];
        if (zholes_size)
            realsize -= zholes_size[j];

        //printk("zone(%lu): %lu pages.\n", j, size);
        zone->size = size;
        zone->name = zone_names[j];
        zone->lock = SPIN_LOCK_UNLOCKED;
        zone->zone_pgdat = pgdat;
        zone->free_pages = 0;
        zone->need_balance = 0;
        if (!size)
            continue;

        /*
         * The per-page waitqueue mechanism uses hashed waitqueues
         * per zone.
         */
//        zone->wait_table_size = wait_table_size(size);
//        zone->wait_table_shift =
//                BITS_PER_LONG - wait_table_bits(zone->wait_table_size);
//        zone->wait_table = (wait_queue_head_t *)
//                alloc_bootmem_node(pgdat, zone->wait_table_size
//                                          * sizeof(wait_queue_head_t));
//
//        for(i = 0; i < zone->wait_table_size; ++i)
//            init_waitqueue_head(zone->wait_table + i);

        pgdat->nr_zones = j+1;

        mask = (realsize / zone_balance_ratio[j]);
        if (mask < zone_balance_min[j])
            mask = zone_balance_min[j];
        else if (mask > zone_balance_max[j])
            mask = zone_balance_max[j];
        zone->pages_min = mask;
        zone->pages_low = mask*2;
        zone->pages_high = mask*3;

        zone->zone_mem_map = mem_map + offset;
        zone->zone_start_mapnr = offset;
        zone->zone_start_paddr = zone_start_paddr;

        if ((zone_start_paddr >> PAGE_SHIFT) & (zone_required_alignment-1)){
            //printk("BUG: wrong zone alignment, it will crash\n");
        }

        /*
         * Initially all pages are reserved - free ones are freed
         * up by free_all_bootmem() once the early boot process is
         * done. Non-atomic initialization, single-pass.
         */
        for (i = 0; i < size; i++) {
            struct page *page = mem_map + offset + i;
            set_page_zone(page, nid * MAX_NR_ZONES + j);
            set_page_count(page, 0);
            SetPageReserved(page);
            INIT_LIST_HEAD(&page->list);
//            if (j != ZONE_HIGHMEM)
//                set_page_address(page, __va(zone_start_paddr));
            zone_start_paddr += PAGE_SIZE;
        }

        offset += size;
        for (i = 0; ; i++) {
            unsigned long bitmap_size;

            INIT_LIST_HEAD(&zone->free_area[i].free_list);
            if (i == MAX_ORDER-1) {
                zone->free_area[i].map = NULL;
                break;
            }

            /*
             * Page buddy system uses "index >> (i+1)",
             * where "index" is at most "size-1".
             *
             * The extra "+3" is to round down to byte
             * size (8 bits per byte assumption). Thus
             * we get "(size-1) >> (i+4)" as the last byte
             * we can access.
             *
             * The "+1" is because we want to round the
             * byte allocation up rather than down. So
             * we should have had a "+7" before we shifted
             * down by three. Also, we have to add one as
             * we actually _use_ the last bit (it's [0,n]
             * inclusive, not [0,n[).
             *
             * So we actually had +7+1 before we shift
             * down by 3. But (n+8) >> 3 == (n >> 3) + 1
             * (modulo overflows, which we do not have).
             *
             * Finally, we LONG_ALIGN because all bitmap
             * operations are on longs.
             */
            bitmap_size = (size-1) >> (i+4);
            bitmap_size = LONG_ALIGN(bitmap_size+1);
            zone->free_area[i].map =
                    (unsigned long *) alloc_bootmem_node(pgdat, bitmap_size);
        }
    }
    build_zonelists(pgdat);
}
void free_area_init(unsigned long *zones_size)//用于设置UMA体系结构
{
    free_area_init_core(0, &contig_page_data, &mem_map, zones_size, 0, 0, 0);
}

static void __free_pages_ok (struct page *page, unsigned int order)
{
    unsigned long index, page_idx, mask, flags;
    free_area_t *area;
    struct page *base;
    zone_t *zone;

    /*
     * Yes, think what happens when other parts of the kernel take
     * a reference to a page in order to pin it for io. -ben
     */
//    if (PageLRU(page)) {
//        if (unlikely(in_interrupt()))
//            BUG();
//        lru_cache_del(page);
//    }

    if (page->buffers)
        BUG();
    if (page->mapping)
        BUG();
    if (!VALID_PAGE(page))
        BUG();
    if (PageLocked(page))
       BUG();
    if (PageActive(page))
        BUG();
    page->flags &= ~((1<<PG_referenced) | (1<<PG_dirty));

//    if (current->flags & PF_FREE_PAGES)
//        goto local_freelist;
//back_local_freelist:

    zone = page_zone(page);

    mask = (~0UL) << order;
    base = zone->zone_mem_map;
    page_idx = page - base;
    if (page_idx & ~mask)
        BUG();
    index = page_idx >> (1 + order);

    area = zone->free_area + order;

    spin_lock_irqsave(&zone->lock, flags);

    zone->free_pages -= mask;

    while (mask + (1 << (MAX_ORDER-1))) {
        struct page *buddy1, *buddy2;

        if (area >= zone->free_area + MAX_ORDER)
            BUG();
        if (!__test_and_change_bit(index, area->map))
            /*
             * the buddy page is still allocated.
             */
            break;
        /*
         * Move the buddy up one level.
         * This code is taking advantage of the identity:
         * 	-mask = 1+~mask
         */
        buddy1 = base + (page_idx ^ -mask);
        buddy2 = base + page_idx;
        if (BAD_RANGE(zone,buddy1))
            BUG();
        if (BAD_RANGE(zone,buddy2))
            BUG();

        list_del(&buddy1->list);
        mask <<= 1;
        area++;
        index >>= 1;
        page_idx &= mask;
    }
    list_add(&(base + page_idx)->list, &area->free_list);

    spin_unlock_irqrestore(&zone->lock, flags);
    return;

//local_freelist:
//    if (current->nr_local_pages)
//        goto back_local_freelist;
//    if (in_interrupt())
//        goto back_local_freelist;
//
//    list_add(&page->list, &current->local_pages);
//    page->index = order;
//    current->nr_local_pages++;
}

void __free_pages(struct page *page, unsigned int order)
{
    if (!PageReserved(page) && put_page_testzero(page))
        __free_pages_ok(page, order);
}

void free_pages(unsigned long addr, unsigned int order)
{
    if (addr != 0)
        __free_pages(virt_to_page(addr), order);
}

static struct page * rmqueue(zone_t *zone, unsigned int order)
{
    free_area_t * area = zone->free_area + order;
    unsigned int curr_order = order;
    struct list_head *head, *curr;
    unsigned long flags;
    struct page *page;

    spin_lock_irqsave(&zone->lock, flags);
    do {
        head = &area->free_list;
        curr = head->next;

        if (curr != head) {
            unsigned int index;

            page = list_entry(curr, struct page, list);
            if (BAD_RANGE(zone,page))
                BUG();
            list_del(curr);
            index = page - zone->zone_mem_map;
            if (curr_order != MAX_ORDER-1)
                MARK_USED(index, curr_order, area);
            zone->free_pages -= 1UL << order;

            page = expand(zone, page, index, order, curr_order, area);
            spin_unlock_irqrestore(&zone->lock, flags);

            set_page_count(page, 1);
            if (BAD_RANGE(zone,page))
                BUG();
            if (PageLRU(page))
            BUG();
            if (PageActive(page))
                BUG();
            return page;
        }
        curr_order++;
        area++;
    } while (curr_order < MAX_ORDER);
    spin_unlock_irqrestore(&zone->lock, flags);

    return NULL;
}

/*
 * This is the 'heart' of the zoned buddy allocator:
 */
struct page * __alloc_pages(unsigned int gfp_mask, unsigned int order, zonelist_t *zonelist)
{
    unsigned long min;
    zone_t **zone, * classzone;
    struct page * page;

    zone = zonelist->zones;
    classzone = *zone;
    if (classzone == NULL)
        return NULL;
    min = 1UL << order;
    for (;;) {
        zone_t *z = *(zone++);
        if (!z)
            break;

        min += z->pages_low;
        if (z->free_pages > min) {
            page = rmqueue(z, order);
            if (page)
                return page;
        }
    }
    return NULL;
//    classzone->need_balance = 1;
//    mb();
//    if (waitqueue_active(&kswapd_wait))
//        wake_up_interruptible(&kswapd_wait);
//
//    zone = zonelist->zones;
//    min = 1UL << order;
//    for (;;) {
//        unsigned long local_min;
//        zone_t *z = *(zone++);
//        if (!z)
//            break;
//
//        local_min = z->pages_min;
//        if (!(gfp_mask & __GFP_WAIT))
//            local_min >>= 2;
//        min += local_min;
//        if (z->free_pages > min) {
//            page = rmqueue(z, order);
//            if (page)
//                return page;
//        }
//    }
//
//    /* here we're in the low on memory slow path */
//
//    rebalance:
//    if (current->flags & (PF_MEMALLOC | PF_MEMDIE)) {
//        zone = zonelist->zones;
//        for (;;) {
//            zone_t *z = *(zone++);
//            if (!z)
//                break;
//
//            page = rmqueue(z, order);
//            if (page)
//                return page;
//        }
//        return NULL;
//    }
//
//    /* Atomic allocations - we can't balance anything */
//    if (!(gfp_mask & __GFP_WAIT))
//        return NULL;
//
//    page = balance_classzone(classzone, gfp_mask, order, &freed);
//    if (page)
//        return page;
//
//    zone = zonelist->zones;
//    min = 1UL << order;
//    for (;;) {
//        zone_t *z = *(zone++);
//        if (!z)
//            break;
//
//        min += z->pages_min;
//        if (z->free_pages > min) {
//            page = rmqueue(z, order);
//            if (page)
//                return page;
//        }
//    }
//
//    /* Don't let big-order allocations loop */
//    if (order > 3)
//        return NULL;
//
//    /* Yield for kswapd, and try again */
//    yield();
//    goto rebalance;
}

struct page *_alloc_pages(unsigned int gfp_mask, unsigned int order)
{
    return __alloc_pages(gfp_mask, order,
                         contig_page_data.node_zonelists+(gfp_mask & GFP_ZONEMASK));
}

/*
 * Common helper functions.
 */
unsigned long __get_free_pages(unsigned int gfp_mask, unsigned int order)
{
    struct page * page;

    page = alloc_pages(gfp_mask, order);
    if (!page)
        return 0;
    return (unsigned long) page_address(page);
}